package com.ruoyi.framework.web.service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.mapper.H5RegisterMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.websocket.WebSocketManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * 注册校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private H5RegisterMapper h5RegisterMapper;

    /**
     * 注册
     */
    public String register(RegisterBody registerBody)
    {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (!userService.checkUserNameUnique(sysUser))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        else
        {
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    /**
     * H5页面简单注册
     * @param registerBody
     * @return
     */
    @Transactional(rollbackFor = Throwable.class)
    public String registerNew(RegisterBody registerBody)
    {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);

        if(StringUtils.isEmpty(registerBody.getNickName()) || StringUtils.isEmpty(registerBody.getCity()) || StringUtils.isEmpty(registerBody.getProvince()) || StringUtils.isEmpty(registerBody.getDistrict())) {
            msg = "请完善企业名称及企业所在区县信息";
            return msg;
        }

        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled)
        {
            validateCaptcha(username, registerBody.getCode(), registerBody.getUuid());
        }

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (!userService.checkUserNameUnique(sysUser))
        {
            // 如果账号已经存在，更新该账号的密码，以用户当前输入的为准。
            // 用户表的数据导入了一部分，默认给了每个导入用户一个默认密码，如果用户不知道自己的账号已经在系统当中，则会到此注册
            //msg = "保存用户'" + username + "'失败，注册账号已存在";
            userService.resetUserPwd(username, SecurityUtils.encryptPassword(password));
        }
        else
        {
            sysUser.setNickName(registerBody.getNickName());
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUser.setRemark("企业人员");
            sysUser.setProvince(registerBody.getProvince());
            sysUser.setCity(registerBody.getCity());
            sysUser.setDistrict(registerBody.getDistrict());
            boolean regFlag = userService.registerUser(sysUser);
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                // 查询新的用户id，设置一个普通角色
                Long userId = h5RegisterMapper.queryRegisterUserId(sysUser.getUserName());
                if(userId == null) {
                    msg = "注册失败,请联系系统管理人员";
                }
                else {
                    // 普通角色
                    h5RegisterMapper.insertRegisterUserRole(userId, 2L);
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
                    //发送消息更新大屏数据中的企业总数
                    String province = sysUser.getProvince();
                    String city = sysUser.getCity();
                    Long enterpriseTotal1 = userService.getEnterpriseTotal(province, city, null);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("appealType", null);
                    jsonObject.put("serviceGrade", null);
                    jsonObject.put("problemTotal", null);
                    jsonObject.put("enterpriseTotal", enterpriseTotal1);
                    jsonObject.put("settledTotal", null);
                    jsonObject.put("settledRate", null);
                    jsonObject.put("serviceState", null);
                    jsonObject.put("enterpriseSatisfaction", null);
                    jsonObject.put("citiesAppealQuantity", null);
                    Set<String> sessionKeys1 = WebSocketManager.getSessionKeysByArea(city);
                    for (String sessionKey : sessionKeys1) {
                        WebSocketManager.sendMessageToKey(sessionKey, jsonObject.toString());
                    }

                    Long enterpriseTotal2 = userService.getEnterpriseTotal(province, null, null);
                    jsonObject.put("enterpriseTotal", enterpriseTotal2);
                    Set<String> sessionKeys2 = WebSocketManager.getSessionKeysByArea(province);
                    for (String sessionKey : sessionKeys2) {
                        WebSocketManager.sendMessageToKey(sessionKey, jsonObject.toString());
                    }
                }
            }
        }
        return msg;
    }


    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }
}
